define(function(require, exports, module) {
	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js");
	require("resource/font-awesome-4.7.0/css/font-awesome.min.css");
	require('resource/font-awesome-4.7.0/css/icomoon.css');
	require("resource/js/component/tree.js");
	var EUtil = require("resource/js/component/easyutil.js");
	var ajax = require("resource/js/component/ajax.js");
	var userIds="";
	var initThisPage = function(params) {
		indexApp.setUserIds = [];
		var key = $("#processKey").val();
		//定义条件选择框
		$('#conditions').combobox({
			valueField: 'branch_id',
			textField: 'branch_expdesc',
			editable:false,
			onLoadSuccess : function(){
				if($('#conditions').combobox('getData')&&$('#conditions').combobox('getData').length>0){
					$('#conditions').combobox('select',$('#conditions').combobox('getData')[0].branch_id);
				}
	        },
			onSelect: function(newValue) {
				ajax.init().success(function(code, msg, data) {
					if (data && data.total != undefined && data.total > 0) {
						$('#connodeinfodatagrid').datagrid('loadData', data.rows);
					} else {
						$('#connodeinfodatagrid').datagrid('loadData', []);
					}
				}).post(BASEPATH + "/oa/act/actExProcessBranch/queryActBussSubSetByPage.htm", {
					processKey: key,
					branchId: newValue.branch_id
				});
			},
		});
		initNodePage();
		initConditionUsers();
		initBtnEvent();
		//去重设置
		ajax.init().success(function(code,msg,data){
			$('#distinct').combobox({
				 valueField: 'distinct',
			     textField: 'text',
			     data:[{'distinct':0,'text':'不开启去重'},{'distinct':1,'text':'连续审批人去重'}],
			     onChange:function(value,old){
			    	 changeDistinctSetting(value);
			     },
			     value:data.distinct
			});
		}).post(BASEPATH+'/oa/act/userProcess/queryUserProcessSetting.htm?key='+key);
	};
	function changeDistinctSetting(value){
		ajax.init().success(function(code,msg,data){
			$.messager.show({
				title:'系统消息',
				msg:msg,
				timeout:1000,
				showType:'slide'
			})
		}).post(BASEPATH+'/oa/act/userProcess/updateUserProcessSetting.htm',{
			distinct:value,
			key:$("#processKey").val()
		})
	}
	var initBtnEvent = function(){
		//改变非条件设置状态
		$("#updateNoCoditionStatus").unbind('click');
		$("#updateNoCoditionStatus").bind('click', function() {
			updateNoConditionStatus(this);
		});

		//分条件按钮
		$("#setCondition").unbind('click');
		$("#setCondition").bind('click', function() {
			setProcessCondition(BASEPATH + "/view/oa/act/approval/progress/select");
		});
		$("#deleteCondition").unbind('click');
		$("#deleteCondition").bind('click', function() {
			updateConditionStatus(this, '删除');
		});
		$("#updateConditionStatus").unbind('click');
		$("#updateConditionStatus").bind('click', function() {
			updateConditionStatus(this, '设置');
		});
	}
	//初始化非条件域
	var initNodePage = function() {
		var status = 0;
		if(userIds!="") userIds="";
		ajax.init().success(function(code, msg, data) {
			for (var i=1;i<data.total;i++) {
				if (data.rows[i].status == "1") {
					status = 1;
				}
				if(data.rows[i].approvalId!=undefined){
					userIds+=data.rows[i].approvalId;
					break;
				}
			}
			if(userIds==""){
				status=1;
			}
			if (data.total != undefined && data.total > 0) {
				$('#nodeinfodatagrid').datagrid('loadData', data.rows);
			} else {
				$('#nodeinfodatagrid').datagrid('loadData', []);
			}

			if (status == 0) {
				$("#bftj_status").text('已启用');
				$("#updateNoCoditionStatus").text('停用');
				$("#updateNoCoditionStatus").attr("status", 1);
			} else {
				$("#bftj_status").text('未启用');
				$("#updateNoCoditionStatus").text('启用');
				$("#updateNoCoditionStatus").attr("status", 0);
			}
		}).post(BASEPATH + "/oa/act/actExBuss/queryActBussDefByPage.htm", {
			processKey: $("#processKey").val()
		});
	};

	//启用|停用非条件设置
	var updateNoConditionStatus = function(obj) {
		if(userIds==""){
			$.messager.alert("系统提示", "请设置流程处理人");
		}else{
			ajax.init().success(function(code, msg, data) {
				initNodePage();
			}).post(BASEPATH + "/oa/act/actExUserDef/startSet.htm", {
				checkeds: $("#processKey").val(),
				status: $(obj).attr("status")
			});
		}
	};

	//设置非分条件审批人
	var setProcessPerson = function(nodeId, nodeNum, index) {
		$(".setProcessPersonDlg").remove();
		$("#formdlg").children().remove();
		setProcessPerson.dlg = $("<div class='setProcessPersonDlg'><div>").appendTo($("body")).dialog({
			title: "审核人设置",
			width: 800,
			height: 550,
			closed: false,
			cache: true,
			modal: true,
			href: BASEPATH + "/view/oa/act/approval/progress/set",
			onLoad: function() {
				$("#setUser").html("");
				$("#nodeNum").val(nodeNum);
				$("#processKey").val($('#processKey').val());
				$("#nodeId").val(nodeId);
				indexApp.setUserIds = [];
				seajs.use("oa/act/approval/progress/js/set", function(set) {
					set.init('noCondition');
				});
			},
			buttons: [{
				text: '重置',
				iconCls: 'icon-reload',
				accessKey: {
					akey: 18,
					mkey: 83
				},
				handler: function() {
					indexApp.setUserIds = [];
					$("#setUser").html("");
				}
			}, {
				text: '保存',
				iconCls: 'icon-ok',
				accessKey: {
					akey: 18,
					mkey: 83
				},
				handler: function() {
					using(["form"], function() {
							ajax.init().success(function(code, msg, data) {
								setProcessPerson.dlg.dialog("close");
								$.messager.show({
									title: '系统提示',
									msg: msg,
									timeout: 5000,
									showType: 'slide'
								});
								initNodePage();
							}).error(function(code, msg, data) {
								$.messager.alert("系统提示", msg);
							}).post(BASEPATH + "/oa/act/actExUserDef/setDealUsers.htm", {
										setUserIds: JSON.stringify(indexApp.setUserIds),
										processKey: $('#processKey').val(),
										isDefined: $("#isDefined").val(),
										nodeId: $("#nodeId").val(),
										orderNum: parseInt(index)
							});
					});
				}
			}, {
				text: '关闭',
				addClass: 'l-btn-red',
				iconCls: 'icon-not',
				id: "del",
				accessKey: {
					akey: 18,
					mkey: 67
				},
				handler: function() {
					setProcessPerson.dlg.dialog('close');
				}
			}]
		});
	};

	//设置分条件审批人
	var setConditionsProcessPerson = function(nodeId,nodeNum,index) {
		$(".setProcessPersonDlg").remove();
		$("#formdlg").children().remove();
		setConditionsProcessPerson.dlg = $("<div class='setProcessPersonDlg'><div>").appendTo($("body")).dialog({
			title: "审核人设置",
			width: 800,
			height: 550,
			closed: false,
			cache: true,
			modal: true,
			href: BASEPATH + "/view/oa/act/approval/progress/set",
			onLoad: function() {
				$("#setUser").html("");
				$("#nodeNum").val(nodeNum);
				$("#nodeId").val(nodeId);
				$("#processKey").val($('#processKey').val());
				$("#branchId").val($("#conditions").combobox('getValue'));
				indexApp.setUserIds = [];
				seajs.use("oa/act/approval/progress/js/set", function(set) {
					set.init('condition');
				});
			},
			buttons: [{
				text: '重置',
				iconCls: 'icon-reload',
				accessKey: {
					akey: 18,
					mkey: 83
				},
				handler: function() {
					indexApp.setUserIds = [];
					$("#setUser").html("");
				}
			}, {
				text: '保存',
				iconCls: 'icon-ok',
				accessKey: {
					akey: 18,
					mkey: 83
				},
				handler: function() {
					using(["form"], function() {
						ajax.init().success(function(code, msg, data) {
							var setUser = $("#setUser").html();
							setConditionsProcessPerson.dlg.dialog("close");
							initConditionUsers();
							ajax.init().success(function(code, msg, data) {//保存成功后重新加载条件框，branchId为当前选中的条件
								if (data && data.total != undefined && data.total > 0) {
									$('#connodeinfodatagrid').datagrid('loadData', data.rows);
								} else {
									$('#connodeinfodatagrid').datagrid('loadData', []);
								}
							}).post(BASEPATH + "/oa/act/actExProcessBranch/queryActBussSubSetByPage.htm", {
								processKey: $("#processKey").val(),
								branchId: $("#conditions").combobox('getValue')
							});
							$.messager.show({
								title: '系统提示',
								msg: '保存成功',
								timeout: 5000,
								showType: 'slide'
							});
						}).error(function(code, msg, data) {
							$.messager.alert('系统提示', msg);
						}).post(BASEPATH + "/oa/act/actExProcessBranch/setDealUsers.htm", {
							setUserIds: JSON.stringify(indexApp.setUserIds),
							branchId: $("#conditions").combobox('getValue'),
							processKey: $("#processKey").val(),
							nodeId: $("#nodeId").val(),
							orderNum: parseInt(index)
						});
					});
				}
			}, {
				text: '关闭',
				addClass: 'l-btn-red',
				iconCls: 'icon-not',
				id: "del",
				accessKey: {
					akey: 18,
					mkey: 67
				},
				handler: function() {
					setConditionsProcessPerson.dlg.dialog('close');
				}
			}]
		});
	};

	//选择条件配置
	var setProcessCondition = function(baseUrl) {
		var branchValId = $("#branchValId").val();
		if (branchValId != undefined && branchValId != null && branchValId != '' && branchValId != 'undefined') {
			$.messager.show({
				title: '系统提示',
				msg: '条件已选择，如需修改，请点击【删除】按钮，删除当前配置.',
				timeout: 5000,
				showType: 'slide'
			});
			return;
		} else {
			$("#formdlg").dialog({
				iconCls: 'icon-save',
				title: '分条件审批设置',
				href: baseUrl,
				onLoad: function() {
					$("#conditionForm").show();
					$(".approvaloption").hide();
					$("#conditionForm .tabseach").html('');
					$("#setSub").linkbutton('enable');
					$("#nodeNumes").val($("#nodeNum").val());
					using(["form"], function() {
						ajax.init().success(function(code, msg, data) {
							$('#conditionForm>div').html('');
							if (data.item && data.item.length > 0) {
								for (var it in data.item) {
									if (data.item[it].showtype && data.item[it].showtype == 'select') {
										var selectArr = data.detail[data.item[it].colkey];
										var htm = $("<div></div>");
										for (var m in selectArr) {
											htm.append("<span>" + selectArr[m].text + "</span>");
										}
										$('#conditionForm>div').append(
											'<div style="border-bottom: 1px solid #ddd;padding: 5 0 10 20;">' +
											'<div class="seTitle">' +
											'<input type="hidden" name="dataonchange" value="' + data.item[it].dataonchange + '"/>' +
											'<input type="hidden" name="para" value=\'' + JSON.stringify(selectArr) + '\'/>' +
											'<input style="max-width:16px;position: relative;top: 6px;margin: 0;" type="radio" name="radio" class="seInput" value="' + data.item[it].colkey + '"  col="' + data.item[it].colname + '">' +
											'<label><span style="padding: 0px 5px;color: red;">*</span>' + data.item[it].colnamech + '</label>' +
											'</div>' +
											'<div class="" style="clear:both;padding-left: 22px;">' +
											'<div style="color: #999;padding:5px 0px 12px 0px;"><span>选项内容将会作为审批条件</span></div>' +
											'<div class="listTypebackground">' + htm.html() + '</div>' +
											'</div>' +
											'</div>' +
											'</div>');


									} else if ((data.item[it].showtype && data.item[it].showtype == 'number') || (data.item[it].showtype && data.item[it].showtype == 'integer')) {
										$('#conditionForm>div').append(
											'<div style="border-bottom: 1px solid #ddd;padding: 5 0 10 20;">' +
											'<div class="seTitle">' +
											'<input style="max-width:16px;position: relative;top: 6px;margin: 0;" type="radio" name="radio" class="seInput" value="' + data.item[it].colkey + '"  col="' + data.item[it].colname + '">' +
											'<label><span style="padding: 0px 5px;color: red;">*</span>' + data.item[it].colnamech + '</label>' +
											'</div>' +
											'<div class="" style="clear:both;padding-left:22px;">' +
											'<div style="color:#999;padding-top:5px;"><span>请输入' + data.item[it].colnamech + '的分隔数字</span></div>' +
											'<div><span class="listlast"><input class="easyui-numberbox" value="0" type="text" data-options="required:true,precision:1" /></span><span class="listlast"><span style="padding:0px 5px; position: relative; top:5px;">≤</span><input value="3" class="easyui-numberbox" type="text" data-options="required:true,precision:1" /></span>' +
											'<img style="position: relative;top: 12px; padding:0px 10px;width:20px;height:20px;" name="adimg" src="' + BASEPATH + '/resource/js/easyui/themes/icons/edit_add.png"/>' +
											'<img name="delimg" src="' + BASEPATH + '/resource/js/easyui/themes/icons/edit_remove.png" style="display:none;position: relative;top: 12px;width:20px;height:20px;" num="2"/>' +
											'</div>' +
											'</div>' +
											'</div>' +
											'</div>');
									}
								}
							} else {
								$('#conditionForm>div').html("<div><span style='padding:0px 25px;line-height: 30px;'>没有可以设置的审批条件</span></div>");
								$("#setSub").linkbutton('disable');
							}

							$.parser.parse('#conditionForm>div');
							$("img[name='adimg']").click(function() {
								var num = parseInt($(this).next().attr("num"));
								var httext = $("<span class='listlast' name='listlast" + num + "'></span>");
								var tex = $('<input type="text" class="easyui-numberbox" data-options="required:true,precision:1" />');
								httext.append(tex);
								$(this).before(httext);
								tex.numberbox({}).after("<span style='padding:0px 5px;position: relative; top:5px;'>≤</span>");
								$(this).next().css("display", "inline-block");

								$(this).next().attr("num", (num + 1));
							});
							$("img[name='delimg']").click(function() {
								var num = parseInt($(this).attr("num"));
								num = num - 1;
								$(this).parent().find("span[name=listlast" + num + "]").remove();
								$(this).before().before();
								$(this).attr("num", num);
								if (num <= 2) {
									$(this).css("display", "none");
								}
							});

						}).error(function(code, msg, data) {
							$.messager.alert('系统提示', msg);
						}).post(BASEPATH + "/oa/act/actExProcessBranch/getSelectPage.htm", {
							processKey: $("#processKey").val(),
							isDefined: $("#isDefined").val()
						});
					});
				},
				buttons: [{
					text: '确定',
					iconCls: 'icon-ok',
					id: 'setSub',
					accessKey: {
						akey: 18,
						mkey: 83
					},
					handler: function() {
						if ($("input[name=radio]:checked").length > 0) {
							var numboxArr = $("input[name=radio]:checked").parent().parent().find("input[class^='easyui-']");
							var arr = [];
							var obj = {};
							if (numboxArr.length > 0) {
								for (var m = 0; m < numboxArr.length; m++) {
									arr.push($(numboxArr[m]).numberbox("getValue"));
									if (!$(numboxArr[m]).numberbox("isValid")) {
										$.messager.alert('系统提示', "请填写相关数据");
										return;
									}
								}
								var array2 = arr.concat();
								array2.sort(function(a, b) {
									return a - b;
								});
								for (var i = 0; i < arr.length; i++) {
									if (arr[i] != array2[i]) {
										$.messager.alert('系统提示', "数据填写有误");
										return;
									}
								}

								obj.list = arr.join(',');
								obj.colkey = $("input[name=radio]:checked").val();
								obj.process_key = $("#processKey").val();
							} else {
								obj.dataonchange = $('input:radio:checked').siblings("input[name='para']").val();
								obj.process_key = $("#processKey").val();
								obj.colkey = $("input[name=radio]:checked").val();
							}
							$("#branchValId").val($("input[name=radio]:checked").attr("col"));
							obj.isDefined = $("#isDefined").val();
							ajax.init().success(function(code, msg, data) {
								initConditionUsers();
								$("#formdlg").dialog("close");
							}).error(function(code, msg, data) {
								$.messager.alert('系统提示', msg);
							}).post(BASEPATH + "/oa/act/actExProcessBranch/saveSubProcessSet.htm", obj);

						}
					}
				}, {
					text: '取消',
					addClass: 'l-btn-red',
					accessKey: {
						akey: 18,
						mkey: 67
					},
					handler: function() {
						$("#formdlg").dialog("close");
					}
				}]
			});
			$('#formdlg').dialog('open').dialog('resize',(window.innerHeight-$('#formdlg').dialog("options").height)/2);
			$("#conditionForm").show();
			$(".approvaloption").hide();
		}
	};

	//初始化分条件域
	var initConditionUsers = function() {
		var branchValId = $("#branchValId").val();
		if (branchValId != undefined && branchValId != null && branchValId != '' && branchValId != "undefined") {
			ajax.init().success(function(code, msg, data) {
				var status = 0;
				var is_set = 0;
				if (data.length && data.length > 0) {
					if (data[0].status == '1') {
						status = 1;
					}
					for(var i=0;i<data.length;i++){
						if(data[i].set_status == '1'){
							is_set = 1;
						}else{
							is_set = 0;
						}
					}
				}
				if(!($('#conditions').combobox('getData')&&$('#conditions').combobox('getData').length>0)){
					$('#conditions').combobox('loadData',data);
				}

				 if (is_set == 1) {
					$("#ftj").text("审核人未设置正确");
				 	$("#updateConditionStatus").parent().hide();
					$("#setCondition").parent().hide();
				 	$("#deleteCondition").parent().show();
				 	$("#deleteCondition").css('right', '10px');

				 } else {
					if (status == 1) {
						$("#ftj").text("未启用");
						$("#updateConditionStatus").text("启用");
						$("#updateConditionStatus").attr("status", 0);
						$("#updateConditionStatus").parent().show();
						$("#setCondition").parent().hide();
						$("#deleteCondition").parent().show();
					} else {
						$("#ftj").text("已启用");
						$("#updateConditionStatus").parent().show();
						$("#updateConditionStatus").text("停用");
						$("#updateConditionStatus").attr("status", 1);
						$("#setCondition").parent().hide();
						$("#deleteCondition").parent().show();
					}
				 }
			}).error(function(code, msg, data) {
				$.messager.alert('系统提示', msg);
			}).post(BASEPATH + "/oa/act/actExProcessBranch/querySubSet.htm", {
				branchValId: $("#branchValId").val(),
				isDefined: $("#isDefined").val(),
				processKey: $("#processKey").val()
			});
		} else {
			$("#ftj").text("未设置");
			$("#updateConditionStatus").parent().hide();
			$("#deleteCondition").parent().hide();
			$("#setCondition").parent().show();
		}

	};
	var updateConditionStatus = function(obj, msghead) {
		ajax.init().success(function(code, msg, data) {
			if (msghead == "删除") {
				$.messager.confirm("系统提示", "是否要删除分条件审批？", function(r) {
					if (r) {
						$("#branchValId").val("");
						$('#conditions').combobox('clear');
						$('#conditions').combobox('loadData',[])
						$('#connodeinfodatagrid').datagrid('loadData', []);
						params.branchValId=null;
						initConditionUsers();
					}
				});
			} else {
				$.messager.show({
					title: '系统提示',
					msg: msghead + '成功',
					timeout: 2000,
					showType: 'slide'
				});
				initConditionUsers();
			}
		}).post(BASEPATH + "/oa/act/actExProcessBranch/updateSet.htm?status=" + $(obj).attr("status"), {
			checkeds: $("#processKey").val(),
			isDefined: $("#isDefined").val()
		});
	};
	var params;
	module.exports = {
		init: function(dlg) {
			if(!params){
				params = JSON.parse(window.sessionStorage.ACT_SETUSER_PARAMS);
			}
			var conf = {
				columns: [
					[{
						field: 'definedId',
						title: 'id',
						width: 100,
						align: 'center',
						height: 50,
						hidden: true
					}, {
						field: 'processKey',
						title: '<input style="height:17px;width:17px;" type="radio" disabled>',
						width: 30,
						formatter: function(value, row, index) {
							return '<input name="ck" style="height:17px;width:17px;" type="radio">';
						}
					}, {
						field: 'processNodeId',
						title: '节点编码',
						width: 100,
						align: 'center',
						height: 50,
						hidden: true
					}, {
						field: 'processNodeName',
						title: '节点名称',
						width: 100,
						align: 'center',
						height: 50
					}, {
						field: 'orderNum',
						title: '节点顺序',
						width: 100,
						align: 'center',
						height: 50
					}, {
						field: 'maxApproval',
						title: '最大审批人个数',
						width: 100,
						align: 'center',
						height: 50
					}, {
						field: 'isSequential',
						title: '是否串行',
						width: 100,
						align: 'center',
						height: 50,
						formatter: function(val, row, i) {
							if (row.max_approval > 1 || row.max_approval == -1) {
								return '<span style="color:#c3c0c0">' + '</span>'
							} else {
								return '<span style="color:green">' + val + '</span>'
							}
						}
					}, {
						field: 'approvalId',
						title: '预设的审批人',
						width: 100,
						align: 'center',
						height: 50
					}, {
						field: 'approvalType',
						title: '审批人类型',
						width: 100,
						align: 'center',
						height: 50
					}]
				]
			};

			var buttons = {
				title: {
					_class: "",
					text: params.processName + "-节点"

				},
				btn: [{
					iconCls: 'icon-icon1_32',
					text: "审核人设置",
					url:'/view/oa/act/approval/progress/set',
					needRow: true,
					handler: function(baseUrl, row) {
						if ("PROCESS_START" == row.processNodeId) {
							$.messager.alert("系统提示", "开始节点无法预设审批人！");
							return;
						}
						if(row.maxApproval == 0){
							$.messager.alert("系统提示", "该节点审批人已内置，无法自定义");
							return;
						}
						setProcessPerson(row.processNodeId, row.maxApproval, row.orderNum);
					}
				}]
			};

			var buttons2 = {
				title: {
					_class: "",
					text: '条件选择：<input  id="conditions" name="conditions" class="easyui-combobox">'
				},
				btn: [{
					iconCls: 'icon-icon1_32',
					text: "审核人设置",
					url:'/view/oa/act/approval/progress/set',
					needRow: true,
					handler: function(baseUrl, row) {
						if ("PROCESS_START" == row.processNodeId) {
							$.messager.alert("系统提示", "开始节点无法预设审批人！");
							return;
						}
						if(row.maxApproval == 0){
							$.messager.alert("系统提示", "该节点审批人已内置，无法自定义");
							return;
						}
						setConditionsProcessPerson(row.processNodeId, row.maxApproval, row.orderNum);
					}
				}]
			};
			var datagridconfig = {
				fitColumns: true,
				rownumbers: true,
				toolbar: buttons,
				columns: conf.columns,
				eid: "nodeinfodatagrid",
				pagination: false,
				singleSelect: true,
				check: true,
				pagination: false,
				onClickRow: function(index, row) {
					$(event.target.closest('tr')).find("input[name=ck]").prop("checked", true);
				}
			};

			var datagridconfig2 = {
				fitColumns: true,
				rownumbers: true,
				toolbar: buttons2,
				columns: conf.columns,
				eid: "connodeinfodatagrid",
				pagination: false,
				singleSelect: true,
				check: true,
				onClickRow: function(index, row) {
					$(event.target.closest('tr')).find("input[name=ck]").prop("checked", true);
				}
			};

			using(["datagrid", "combobox","parser","layout","dialog"], function() {
				$.parser.parse('body');
				$('#nodeinfodatagrid').datagrid(datagridconfig);
				EUtil.showBTN(undefined, datagridconfig);
				$('#connodeinfodatagrid').datagrid(datagridconfig2);
				EUtil.showBTN(undefined, datagridconfig2);

				$("#nodeNum").val(params.nodeNum);
				$("#processKey").val(params.processKey);
				$("#branchValId").val(params.branchValId);
				$("#isDefined").val(params.is_defined);
				initThisPage(params);
			});

		}
	}
});
